/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtForest;
import com.thinkgem.jeesite.modules.gt.entity.GtForestPeople;
import com.thinkgem.jeesite.modules.gt.service.GtForestPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtForestService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 经济林面积Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtForest")
public class GtForestController extends BaseController {

	@Autowired
	private GtForestService gtForestService;
	@Autowired
	private GtForestPeopleService gtForestPeopleService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private DictService dictService;
	
	@ModelAttribute
	public GtForest get(@RequestParam(required=false) String id) {
		GtForest entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtForestService.get(id);
		}
		if (entity == null){
			entity = new GtForest();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtForest gtForest,String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		// 日志标题
		// request.setAttribute("title", "查询经济林列表" + gtForest.getAddress());
		
		this.areaService.fetchRegions(model);
		if(null == gtForest.getArea() || StringUtils.isBlank(gtForest.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtForest.setArea(area);
		}
		
		Page<GtForest> page = gtForestService.findPage(new Page<GtForest>(request, response), gtForest); 
		model.addAttribute("page", page);
		model.addAttribute("gtForest", gtForest);
		
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtForestList";
	}

	// 经济林扶贫人列表
	@RequestMapping(value = {"listForestPeople"})
	public String listForestPeople(GtForestPeople gtForestPeople, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		Page<GtForestPeople> page = gtForestPeopleService.findPage(new Page<GtForestPeople>(request, response), gtForestPeople); 
		model.addAttribute("page", page);
		gtForestPeople.setForest(this.gtForestService.get(gtForestPeople.getForest().getId()));
		model.addAttribute("gtForestPeople", gtForestPeople);
		
		return "modules/gt/basic/gtForestPeopleList";
	}
	
	
	@RequestMapping(value = "form")
	public String form(GtForest gtForest, Model model) {
		
		this.areaService.fetchRegions(model);
		
		model.addAttribute("gtForest", gtForest);
		return "modules/gt/basic/gtForestForm";
	}
	
	
	@RequestMapping(value = "formForestPeople")
	public String formForestPeople(GtForestPeople gtForestPeople, Model model) {
		
		gtForestPeople.setForest(this.gtForestService.get(gtForestPeople.getForest().getId()));
		
		List<Dict> helpTypes = DictUtils.getDictList("gt_help_type");
		model.addAttribute("helpTypes", helpTypes);
		
		// 修改时，查询相关信息
		if(StringUtils.isNotBlank(gtForestPeople.getId()))
		{ 
			// 记住菜单id
			String menuId = gtForestPeople.getMenuId();
			gtForestPeople = this.gtForestPeopleService.get(gtForestPeople.getId());
			gtForestPeople.setMenuId(menuId);
		}
		
		model.addAttribute("gtForestPeople", gtForestPeople);
		return "modules/gt/basic/gtForestPeopleForm";
	}

	@RequestMapping(value = "save")
	public String save(GtForest gtForest, String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtForest)){
			return form(gtForest, model);
		}
		if(StringUtils.isBlank(gtForest.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加经济林:" + gtForest.getAddress());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改经济林:" + gtForest.getAddress());
		}
		
		gtForestService.save(gtForest);
		addMessage(redirectAttributes, "保存经济林信息成功");
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtForest/form?menuId=" + gtForest.getMenuId();
		}
		
		return "redirect:"+super.frontPath+"/gt/gtForest/list?menuId=" + gtForest.getMenuId();
	}
	
	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtForestPeople gtForestPeople,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportForestFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportForestFileName");
    	}
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("经济林扶贫信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	//9c65bfefb542491a89dc2aa8723e60ff
        	GtForest gtForest = new GtForest();
        	if(null == gtForest.getArea() || StringUtils.isBlank(gtForest.getArea().getCode()))
    		{
        		if(StringUtils.isEmpty(areaId))
        		{
	    			gtForest.setArea(UserUtils.getUser().getArea());
        		}
        		else
        		{
        			gtForest.setArea(area);
        		}
    		}
        	gtForestPeople.setForest(gtForest);
        	
        	Page<GtForestPeople> page = new Page<GtForestPeople>();
        	/*page.setOrderBy("b.create_date,b.id,a.update_date");*/
        	page.setOrderBy("a2.sort,b.id");
        	gtForestPeople.setPage(page);
        	
        	
        	
            List<GtForestPeople> list = gtForestPeopleService.findList(gtForestPeople);
            
            if(null == list || list.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 5 * 256);
	            sh.setColumnWidth(1, 30 * 256);
	            sh.setColumnWidth(2, 30 * 256);
	            sh.setColumnWidth(3, 10 * 256);
	            sh.setColumnWidth(4, 18 * 256);
	            sh.setColumnWidth(5, 9 * 256);
	            sh.setColumnWidth(6, 30 * 256);
	            sh.setColumnWidth(7, 22 * 256);
	            sh.setColumnWidth(8, 30 * 256);
	            /*sh.setColumnWidth(8, 10 * 256);*/
	            sh.setColumnWidth(9, 10 * 256);
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("序号");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("所属单位");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("建设地点");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("面积（亩）");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("主要树种");
	            cellHeader = rowHeader.createCell(5);
	            cellHeader.setCellValue("姓名");
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("家庭住址");
	            cellHeader = rowHeader.createCell(7);
	            cellHeader.setCellValue("身份证号");
	            cellHeader = rowHeader.createCell(8);
	            cellHeader.setCellValue("方式");
	            /*cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("金额");*/
	            cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("备注");
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            SimpleDateFormat simpleDateFormat = null;
	            // 记录本次经济林信息id，用于区分是不是同一个经济林信息
	            String nowForestId = null;
	            // 本次经济林信息合并单元格开始行数，默认为0；
	            int nowForestBeginRow = 0;
	            // 序号
	            int seq = 1;
	            int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前经济林
	            	GtForestPeople forestPeople = list.get(i);
	            	
	            	// 下一个经济林
	            	GtForestPeople forestPeopleNext = null;
	            	// 存在下一个，则获取下一个，用于查看本次经济林与下一个经济林是否是同一个经济林
	            	if(i+1 < size)
	            	{
	            		forestPeopleNext = list.get(i+1);
	            	}
	            	else
	            	{
	            		forestPeopleNext = null;
	            	}
	            	
	            	Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);
	            	
	            	// 第一次初始化本次经济林id
	            	if(i == 0)
	            	{
	            		nowForestId = forestPeople.getForest().getId();
	            		nowForestBeginRow = 0;
	            		
		                cell.setCellValue(seq);
		                cell = row.createCell(1);
		                cell.setCellValue(forestPeople.getForest().getArea().getName());
		                cell = row.createCell(2);
		                cell.setCellValue(forestPeople.getForest().getAddress());  
		                cell = row.createCell(3);
		                cell.setCellValue(forestPeople.getForest().getForestArea());
		                cell = row.createCell(4);
		                cell.setCellValue(forestPeople.getForest().getTreeType());
	            	}
	            	// 判断
	            	else
	            	{
	            		// 上一个经济林信息id
	            		String lastForestId = list.get(i-1).getForest().getId();
	            		// 本次经济林信息id和上次经济林信息id不一致，则说明本次是新的经济林开始
	            		if(!lastForestId.equals(forestPeople.getForest().getId()))
	            		{
	            			nowForestBeginRow = i;
	            			seq ++;
	    	                cell.setCellValue(seq);
	    	                cell = row.createCell(1);
			                cell.setCellValue(forestPeople.getForest().getArea().getName());
	    	                cell = row.createCell(2);
	    	                cell.setCellValue(forestPeople.getForest().getAddress());  
	    	                cell = row.createCell(3);
	    	                cell.setCellValue(forestPeople.getForest().getForestArea());
	    	                cell = row.createCell(4);
	    	                cell.setCellValue(forestPeople.getForest().getTreeType());
	            		}
	            		
	            	}
	            	
	            	
	                /*cell.setCellValue(seq);
	                cell = row.createCell(1);
	                cell.setCellValue(forestPeople.getForest().getAddress());  
	                cell = row.createCell(2);
	                cell.setCellValue(forestPeople.getForest().getForestArea());
	                cell = row.createCell(3);
	                cell.setCellValue(forestPeople.getForest().getTreeType());*/
	                
	                
	                cell = row.createCell(5);
	                cell.setCellValue(forestPeople.getName());
	                
	                cell = row.createCell(6);
	                // cell.setCellValue(DictUtils.getDictLabel(forestPeople.getJoinType(), "dictType", null));
	                cell.setCellValue(forestPeople.getAddress());
	                
	                cell = row.createCell(7);
	                cell.setCellValue(forestPeople.getIdcard());
	                cell = row.createCell(8);
	                
	                /*cell.setCellValue(DictUtils.getDictLabel(forestPeople.getHelpType(), "gt_help_type", null) 
	                		+ ("o".equals(forestPeople.getHelpType())?"(" + forestPeople.getHelpOther() + ")":""));*/
	                String helpType = forestPeople.getHelpType();
	                if(StringUtils.isEmpty(helpType))
	                {
	                	cell.setCellValue("");
	                }else
	                if(helpType.length() < 2){
	                	cell.setCellValue(DictUtils.getDictLabel(helpType, "gt_help_type", null) 
	                		+ ("o".equals(helpType)?"(" + forestPeople.getHelpOther() + ")":""));
	                }
	                else
	                {
	                	String helpVal = "";
	                	String [] helpArr = helpType.split(",");
	                	for(String help:helpArr)
	                	{
	                		if(StringUtils.isEmpty(help))
	                		{
	                			continue;
	                		}
	                		
	                		helpVal += DictUtils.getDictLabel(help, "gt_help_type", null) + " ";
	                		if("o".equals(help))
	                		{
	                			helpVal += "(" + forestPeople.getHelpOther() + ")";
	                		}
	                	}
	                	cell.setCellValue(helpVal);
	                	
	                }
	                /*cell = row.createCell(9);  
	                cell.setCellValue(null == forestPeople.getMoney()?"0":String.valueOf(forestPeople.getMoney()));*/
	                cell = row.createCell(9);  
	                cell.setCellValue(forestPeople.getRemarks());
	                
	                
	                // 对比本次经济林和下一个经济林是否是同一个，
	            	if(i > 0)
	            	{
	            		nowForestId = forestPeople.getForest().getId();
	            		// 没有下一个经济林信息或者下一个经济林信息和本次经济林信息不是同一个，则开始合并单元格
	            		if(null == forestPeopleNext || !nowForestId.equals(forestPeopleNext.getForest().getId()))
	            		{
	            			for(int col = 0; col < 5; col ++)
	            			{
		            			// 合并单元格，开始行为 nowForestBeginRow + 1，结束行为i + 1(+1是因为第0行为标题)
		            			CellRangeAddress cellAddr = new CellRangeAddress(nowForestBeginRow + 1, i + 1, col, col);
		            			sh.addMergedRegion(cellAddr);
	            			}
	            		}
	            	}
	                
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
        
        // 保存日志
        request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	
	@RequestMapping(value = "saveForestPeople")
	public String saveForestPeople(GtForestPeople gtForestPeople, String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		
		
		if(StringUtils.isBlank(gtForestPeople.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加经济林扶贫人信息:" + gtForestPeople.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改经济林扶贫人信息:" + gtForestPeople.getName());
		}
		
		gtForestPeopleService.save(gtForestPeople);
		addMessage(redirectAttributes, "保存经济林贫困人口信息成功");
		
		// model.addAttribute("gtForestPeople", gtForestPeople);
		// redirectAttributes.addFlashAttribute("gtForestPeople", gtForestPeople);
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtForest/formForestPeople/?forest.id=" + gtForestPeople.getForest().getId() + "&menuId=" + gtForestPeople.getMenuId();
		}
		else
		{
			return "redirect:"+super.frontPath+"/gt/gtForest/listForestPeople/?forest.id=" + gtForestPeople.getForest().getId() + "&menuId=" + gtForestPeople.getMenuId();
		}
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtForest gtForest,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		this.gtForestPeopleService.deleteByForestId(gtForest.getId());
		
		gtForestService.delete(gtForest);
		
		// 日志标题
		request.setAttribute("title", "删除经济林(及其下扶贫人):" + gtForest.getId());
		
		addMessage(redirectAttributes, "删除经济林信息成功");
		return "redirect:"+super.frontPath+"/gt/gtForest?menuId=" + gtForest.getMenuId();
	}
	
	@RequestMapping(value = "deleteForestPeople")
	public String deleteForestPeople(GtForestPeople gtForestPeople,HttpServletRequest request, HttpServletResponse response,  RedirectAttributes redirectAttributes) {
		
		this.gtForestPeopleService.delete(gtForestPeople);
		addMessage(redirectAttributes, "删除经济林贫困人口信息成功");
		
		// 日志标题
		request.setAttribute("title", "删除经济林贫困人:" + gtForestPeople.getId());
				
		return "redirect:"+super.frontPath+"/gt/gtForest/listForestPeople?forest.id=" + gtForestPeople.getForest().getId() + "&menuId=" + gtForestPeople.getMenuId();
	}

}